using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using ThunderFireUnityEx;
using Newtonsoft.Json;

#if UNITY_EDITOR
using UnityEditor;
#endif

public interface ILocalization
{
    bool ignoreLocalization { get; }
    Transform transform { get; }
    void ChangeLanguage(LocalizationHelper.LanguageType language);
}

public interface ILocalizationText : ILocalization
{
    string localizationID { get; }
    string text { get; }
    LocalizationHelper.TextLocalizationType localizationType { get; }
}

[Serializable]
public class LocalizationTextRow
{
    public string key;
    public string[] translates;
}

public class LocalizationHelper
{
    /// <summary>
    /// YooAssets 热更资源加载服务实体
    /// </summary>
    static YooAssetsSystem.YAService_Entity yaservice_entity => YooAssetsSystem.YAService_Entity.Instance;

    static TextAsset json_AOT = null;
    static TextAsset json_HOT = null;

    /// <summary>
    /// 游戏内设置的全局语言
    /// </summary>
    private static LanguageType globalLanguage = LanguageType.None;
    /// <summary>
    /// GameView右上角设置的预览语言
    /// </summary>
    private static LanguageType previewLangugage = LanguageType.None;
    public enum LanguageType
    {
        ShowKey = -3,
        NoWord = -2,
        None = -1,
        Chinese_Simplified = 0,
        Chinese_Traditional = 1,
        English = 2,
        Japanese = 3,
        Korean = 4,
        French = 5,
        German = 6,
        Spanish = 7,
        Russian = 8,
        Turkish = 9,
        Portuguese = 10,
        Vietnamese = 11,
        Thai = 12,
        Arabic = 13,
        Italian = 14,
        Indonesian = 15,
    }
    public enum TextLocalizationType
    {
        [InspectorName("静态文本 (Runtime-Use)")]
        RuntimeUse = 0,//不需要程序代码生成的文字
        [InspectorName("动态文本 (Preview)")]
        Preview = 1,//需要程序代码生成的文字
    }

    /// <summary>
    /// 更新所有ILocalization的语言
    /// </summary>
    private static void ChangeILocalization()
    {
#if UNITY_2020_3_OR_NEWER
        ILocalization[] allObjects = UnityEngine.Object.FindObjectsOfType<MonoBehaviour>(true).OfType<ILocalization>().ToArray();
        foreach (var obj in allObjects)
        {
            obj.ChangeLanguage(GetLanguage());
        }
#else
        ILocalization[] allObjects = Resources.FindObjectsOfTypeAll<MonoBehaviour>().OfType<ILocalization>().ToArray();
        foreach (var obj in allObjects)
        {
            if(obj.transform.gameObject.scene.name == UnityEngine.SceneManagement.SceneManager.GetActiveScene().name)
            {
                obj.ChangeLanguage(GetLanguage());
            }
        }
#endif
    }

    protected static void LoadJSON_AOT()
    {
#if UNITY_EDITOR
        // 编辑器状态下使用AssetDatabase加载
        if (!Application.isPlaying)
        {
            json_AOT = AssetDatabase.LoadAssetAtPath<TextAsset>(UXGUIConfig.TextLocalizationJsonPath_AOT);
        }
        else
#endif
        {
            // 运行时使用ResourceManager加载
            json_AOT = ResourceManager.Load<TextAsset>(UXGUIConfig.TextLocalizationJsonPath_AOT);
        }

        if (json_AOT == null)
        {
            Debug.LogError("ReadFromJSON_AOT 找不到配置文件 path: " + UXGUIConfig.TextLocalizationJsonPath_AOT);
            return;
        }
    }

    protected static void LoadJSON_HOT()
    {
#if UNITY_EDITOR
        // 编辑器状态下使用AssetDatabase加载
        if (!Application.isPlaying)
        {
            json_HOT = AssetDatabase.LoadAssetAtPath<TextAsset>(UXGUIConfig.TextLocalizationJsonPath_HOT);
        }
        else
#endif
        {
            // 运行时使用ResourceManager加载
            //json = ResourceManager.Load<TextAsset>(UXGUIConfig.TextLocalizationJsonPath_HOT);
            if (yaservice_entity == null)
            {
                Debug.LogError("ReadFromJSON_HOT yaservice_entity is null");
                return;
            }
            json_HOT = yaservice_entity.LoadTextAsset_Sync(UXGUIConfig.TextLocalizationJsonPath_HOT);
        }

        if (json_HOT == null)
        {
            Debug.LogError("ReadFromJSON_HOT 配置文件为空 path: " + UXGUIConfig.TextLocalizationJsonPath_HOT);
            return;
        }
    }

    public static Sprite LoadSprite_AOT(string spritePath)
    {
        Sprite sp = null;
#if UNITY_EDITOR
        // 编辑器状态下使用AssetDatabase加载
        if (!Application.isPlaying)
        {
            sp = AssetDatabase.LoadAssetAtPath<Sprite>(spritePath);
        }
        else
#endif
        {
            // 移除Assets/前缀，因为ResourceManager.Load不需要
            if (spritePath.StartsWith("Assets/"))
            {
                spritePath = spritePath.Substring(7); // 移除"Assets/"
            }
            sp = ResourceManager.Load<Sprite>(spritePath);
        }
        return sp;
    }

    public static Sprite LoadSprite_HOT(string spritePath, string packageName = "")
    {
        Sprite sp = null;
#if UNITY_EDITOR
        // 编辑器状态下使用AssetDatabase加载
        if (!Application.isPlaying)
        {
            sp = AssetDatabase.LoadAssetAtPath<Sprite>(spritePath);
        }
        else
#endif
        {
            // 运行时使用ResourceManager加载
            //json = ResourceManager.Load<TextAsset>(UXGUIConfig.TextLocalizationJsonPath_HOT);
            if (yaservice_entity == null)
            {
                Debug.LogError($@"LoadSprite_HOT yaservice_entity is null : {spritePath}");
                return null;
            }
            List<Sprite> sprites = yaservice_entity.LoadSprites_Sync(spritePath, packageName);
            if (sprites == null || sprites.Count == 0)
            {
                Debug.LogError($"LoadSprite_HOT 资源文件为空 path: {spritePath}");
                return null;
            }

            sp = sprites[0];
        }

        return sp;
    }

    public static LocalizationTextRow[] ReadFromJSON_AOT()
    {
        if (json_AOT == null)
        {
            LoadJSON_AOT();
        }

        TextAsset json = json_AOT;
        if (json == null)
        {
            Debug.LogError("ReadFromJSON_AOT 配置文件为空 path: " + UXGUIConfig.TextLocalizationJsonPath_AOT);
            return null;
        }
        //Debug.Log("ReadFromJSON_HOT json_AOT.text " + JsonConvert.SerializeObject(json_AOT.text));

        return JsonUtilityEx.FromJson<LocalizationTextRow>(json.text).ToArray();
    }

    public static LocalizationTextRow[] ReadFromJSON_HOT()
    {
        if (json_HOT == null)
        {
            LoadJSON_HOT();
        }

        if (json_HOT == null)
        {
            Debug.LogError("ReadFromJSON_HOT 配置文件为空 path: " + UXGUIConfig.TextLocalizationJsonPath_HOT);
            return null;
        }
        //Debug.Log("ReadFromJSON_HOT json_HOT.text " + JsonConvert.SerializeObject(json_HOT.text));

        return JsonUtilityEx.FromJson<LocalizationTextRow>(json_HOT.text).ToArray();
    }

    public static LanguageType GetLanguage()
    {
        return previewLangugage == LanguageType.None ? globalLanguage : previewLangugage;
    }

    /// <summary>
    /// 切换预览语言
    /// </summary>
    /// <param name="type">语言编号</param>
    public static void SetPreviewLanguage(LanguageType type)
    {
        previewLangugage = type;
        ChangeILocalization();
    }
    /// <summary>
    /// 切换语言（用户接口）
    /// </summary>
    /// <param name="type">语言类型</param>
    public static void SetLanguage(LanguageType type)
    {
        globalLanguage = type;
        ChangeILocalization();
    }
    /// <summary>
    /// 切换语言（用户接口）
    /// </summary>
    /// <param name="type">语言编号</param>
    public static void SetLanguage(int type)
    {
        SetLanguage((LanguageType)type);
    }
}